package com.raptor.trustworthycore.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Map;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * np上传功能工具类
 *
 * @Author renhuan
 * @Date 2021-05-10 10:54
 **/
public class UploadUtil {

  private static final Logger logger = LoggerFactory.getLogger(UploadUtil.class);

  public static String xiegang ="\\";

  /*
   *  写txt文件
   */
  public static void writeTxt(List<Map<String, Object>> list, String fileName, String filePath)
      throws IOException {
    //1. 创建文件
    File file = new File(filePath + xiegang + fileName);
    if (!file.isFile()) {
      file.createNewFile();
    }
    //2. 写入
    BufferedWriter bw = null;
    OutputStreamWriter outputStreamWriter = null;
    FileOutputStream fileOutputStream = null;
    try {
      fileOutputStream = new FileOutputStream(file);
      outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
      bw = new BufferedWriter(outputStreamWriter);
      for (Map<String, Object> map :  list) {
        for (String key : map.keySet()){
          String line = key + "，" + map.get("key") + "\n";
          bw.write(line);
        }
        bw.newLine();
      }
    } catch (IOException e) {
      throw new IOException("writeTxt IOException: " + e);
    } finally {
      if (fileOutputStream != null) {
        try {
          fileOutputStream.close();
        } catch (IOException e) {
          logger.error(String.valueOf(e));
        }
      }
      if (outputStreamWriter != null) {
        try {
          outputStreamWriter.flush();
          outputStreamWriter.close();
        } catch (IOException e) {
          logger.error(String.valueOf(e));
        }
      }
      if (bw != null) {
        try {
          bw.close();
        } catch (IOException e) {
          logger.error(String.valueOf(e));
        }
      }
    }
    logger.info(fileName + "写入txt文件完成");
  }


  /**
   * 判断文件夹是否存在,不存在则逐级创建
   */
  public static Boolean judeDirExists(String localFileDir) {
    if (localFileDir != null && localFileDir.endsWith(UploadUtil.xiegang)) {
      localFileDir = localFileDir.substring(0, localFileDir.lastIndexOf(UploadUtil.xiegang));
    }
    File file = new File(localFileDir);
    if (file.exists() && file.isDirectory()) {
      return true;
    } else {
      logger.warn(localFileDir + "dir not exists, create it ...");
      return file.mkdirs();
    }
  }

  /**
   * 打压缩包
   *
   * @param path 本地路径，斜杠结尾
   * @param downloadMoreName 要压缩的txt文件名
   */
  public static void compressTxt(String path, String downloadMoreName, String zipFileName)
      throws Exception {
    StringBuffer sb = new StringBuffer();
    String[] Str1Array = downloadMoreName.split(",");

    for (int i = 0; i < Str1Array.length; i++) {
      sb.append(path + Str1Array[i] + ",");
    }
    writeZip(path, sb, zipFileName);
  }

  private static void writeZip(String path, StringBuffer sb, String zipFileName) throws Exception {
    String[] files = sb.toString().split(",");
    OutputStream os = null;
    ZipOutputStream zos = null;
    FileOutputStream fileOutputStream = null;
    FileInputStream fileInputStream = null;
    BufferedInputStream bis = null;
    try {
      fileOutputStream = new FileOutputStream(path + zipFileName);
      os = new BufferedOutputStream(fileOutputStream);
      zos = new ZipOutputStream(os);
      byte[] buf = new byte[8192];
      int len;
      for (int i = 0; i < files.length; i++) {
        File file = new File(files[i]);
        if (!file.isFile()) {
          continue;
        }
        ZipEntry ze = new ZipEntry(file.getName());
        zos.putNextEntry(ze);
        //注意此处编码设置
        zos.setEncoding("utf-8");
        fileInputStream = new FileInputStream(file);
        bis = new BufferedInputStream(fileInputStream);
        while ((len = bis.read(buf)) > 0) {
          zos.write(buf, 0, len);
        }
        zos.closeEntry();
      }
      zos.close();

      for (int i = 0; i < files.length; i++) {
        File file = new File(files[i]);
        file.delete();
      }
    } catch (Exception e) {
      throw new Exception("compressTxt and writeZip Exception: " + e);
    } finally {
      if (fileOutputStream != null) {
        try {
          fileOutputStream.close();
        } catch (IOException e) {
          logger.error(e.toString());
        }
      }
      if (os != null) {
        try {
          os.close();
        } catch (IOException e) {
        }
      }
      if (zos != null) {
        try {
          zos.close();
        } catch (IOException e) {
          logger.error(e.toString());
        }
      }
      if (fileInputStream != null){
        try {
          fileInputStream.close();
        } catch (IOException e) {
          logger.error(e.toString());
        }
      }
      if (bis != null){
        try {
          bis.close();
        } catch (IOException e) {
          logger.error(e.toString());
        }
      }
    }
  }


  public static void deletefile(String delpath) {
    try {
      File file = new File(delpath);
      if (!file.isDirectory()) {
        file.delete();
      } else if (file.isDirectory()) {
        String[] fileList = file.list();
        for (int i = 0; i < fileList.length; i++) {
          File delfile = new File(delpath + File.separator + fileList[i]);
          if (!delfile.isDirectory()) {
            delfile.delete();
          } else if (delfile.isDirectory()) {
            deletefile(delpath + File.separator + fileList[i]);
          }
        }
        file.delete();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


}
